const userModel = require('../models/userModel');
const { success, notFound, serverError } = require('../utils/response');

/**
 * 获取用户资料
 */
const getProfile = async (req, res) => {
  try {
    const user = await userModel.findUserById(req.userId);
    if (!user) {
      return notFound(res, '用户不存在');
    }
    success(res, user);
  } catch (err) {
    console.error('获取资料错误:', err);
    serverError(res);
  }
};

/**
 * 更新用户资料
 */
const updateProfile = async (req, res) => {
  try {
    const { username, email } = req.body;
    
    // 验证输入
    if (!username || !email) {
      return notFound(res, '用户名和邮箱都是必填项');
    }
    
    await userModel.updateUserProfile(req.userId, username, email);
    const updatedUser = await userModel.findUserById(req.userId);
    
    success(res, updatedUser, '资料更新成功');
  } catch (err) {
    console.error('更新资料错误:', err);
    serverError(res, '资料更新失败');
  }
};

/**
 * 更新用户头像
 */
const updateAvatar = async (req, res) => {
  try {
    if (!req.file) {
      return notFound(res, '请上传图片文件');
    }
    
    const avatarPath = `/uploads/${req.file.filename}`;
    await userModel.updateUserAvatar(req.userId, avatarPath);
    const updatedUser = await userModel.findUserById(req.userId);
    
    success(res, updatedUser, '头像更新成功');
  } catch (err) {
    console.error('更新头像错误:', err);
    serverError(res, '头像更新失败');
  }
};

module.exports = {
  getProfile,
  updateProfile,
  updateAvatar
};